<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="update-age-head">
    <CommonHead title="修改用户年龄"/>
  </header>

  <br/>

  <!--体: 使用卡片单元格布局修改界面-->
  <section class="update-age-body">

    <!--新年龄: 使用步进器，文字，垂直居中-->
    <van-field name="stepper" label="用户年龄" center>

      <template #input>
        <!--步进器: 双绑用户年龄，最少16，最多60-->
        <van-stepper v-model="age" min="16" max="60"/>
      </template>

      <template #button>
        <!--按钮: 小号，线条，主要蓝，点击时触发-->
        <van-button size="small" type="primary" @click="updateAge">保存</van-button>
      </template>

    </van-field>

  </section>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import {UPDATE_PERSONAL} from '@/api/user';
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, shallowRef} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 用户年龄
let age = shallowRef(router.currentRoute.value.query['age'] + "");

/* ==================== method ==================== */

// method: 修改用户年龄
async function updateAge() {

  // 用户年龄范围校验
  if (age.value < 16 || age.value > 60) {
    showFailToast("用户年龄必须在16-60之间");
    return;
  }

  // 异步调用修改用户信息接口
  let result = await UPDATE_PERSONAL({'age': age.value});
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast("修改成功");
    await router.push("/Personal");
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  }
});

</script>

<style scoped lang="scss">

</style>